package cn.smile.config.spring.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;

/**
 * @Author: 毛苏宇
 * @Description: 数据源配置, 包含事务
 * @Date: Create in 11:03 2019/4/25
 */
//@Configuration
//@EnableTransactionManagement()
public class DataSourceConfig {

    /**
     * 数据源
     * initMethod = "init"方法执行前应该做的一些事情
     * destroyMethod = "close"方法执行完成后的收尾工作
     *
     * @return
     * @throws Exception
     */
    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource druidDataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://140.143.218.23:10084/shiro?useUnicode=true&characterEncoding=utf8");
        druidDataSource.setUsername("shiro");
        druidDataSource.setPassword("maomao123");
        druidDataSource.setFilters("stat,log4j,wall");
        druidDataSource.setMaxActive(500);
        druidDataSource.setInitialSize(2);
        druidDataSource.setMaxWait(60000);
        druidDataSource.setMinIdle(35);
        druidDataSource.setTimeBetweenEvictionRunsMillis(3000);
        druidDataSource.setMinEvictableIdleTimeMillis(300000);
        druidDataSource.setValidationQuery("SELECT *");
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setPoolPreparedStatements(true);
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        return druidDataSource;
    }

    /**
     * 事务管理
     *
     * @return
     * @throws Exception
     */
    @Bean
    public DataSourceTransactionManager transactionManager() throws Exception {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(druidDataSource());
        return dataSourceTransactionManager;
    }

}
